<template>
  <view class="container">
    <!-- 顶部操作栏 -->
    <view class="header">
      <view class="header-title">学校管理</view>
      <view class="add-btn" @click="openForm('add')">
        <text class="iconfont icon-plus"></text>
        <text>新增</text>
      </view>
    </view>
    
    <!-- 筛选弹窗 -->
    <view class="filter-popup" v-if="filterVisible">
      <view class="mask" @click="filterVisible = false"></view>
      <view class="filter-content">
        <view class="filter-header">
          <text class="filter-title">筛选条件</text>
          <text class="close-btn" @click="filterVisible = false">×</text>
        </view>
        <view class="filter-body">
          <view class="filter-item">
            <text class="filter-label">所在城市</text>
            <picker mode="selector" :range="cities" :value="cityIndex" @change="onCityChange">
              <view class="picker-container">
                <text class="picker-text">{{cities[cityIndex].name || '全部城市'}}</text>
                <text class="iconfont icon-arrowdown"></text>
              </view>
            </picker>
          </view>
        </view>
        <view class="filter-footer">
          <view class="btn cancel-btn" @click="filterVisible = false">取消</view>
          <view class="btn confirm-btn" @click="applyFilter">确定</view>
        </view>
      </view>
    </view>
    
    <!-- 表单弹窗 -->
    <view class="form-popup" v-if="formVisible">
      <view class="mask" @click="closeForm"></view>
      <view class="form-content" style="background-color: #fff;z-index: 100;">
        <view class="form-header">
          <text class="form-title">{{formType === 'add' ? '新增学校' : '编辑学校'}}</text>
          <text class="close-btn" @click="closeForm">×</text>
        </view>
        <view class="form-body">
          <view class="form-group">
            <view class="form-item">
              <label class="form-label">学校名称</label>
              <input 
                type="text" 
                class="form-input" 
                v-model="formData.school_name"
                placeholder="请输入学校名称"
              />
              <text class="error-tip" v-if="formErrors.school_name">{{formErrors.school_name}}</text>
            </view>
            <view class="form-item">
              <label class="form-label">所在城市</label>
              <picker mode="selector" :range="cities" :value="cityFormIndex" @change="onFormCityChange">
                <view class="form-input picker-input">
                  {{cities[cityFormIndex] || '请选择城市'}}
                  <text class="iconfont icon-arrowdown"></text>
                </view>
              </picker>
              <text class="error-tip" v-if="formErrors.city_id">请选择城市</text>
            </view>
          </view>
        </view>
        <view class="form-footer">
          <view class="btn cancel-btn" @click="closeForm">取消</view>
          <view class="btn confirm-btn" @click="submitForm">保存</view>
        </view>
      </view>
    </view>
    
    <!-- 删除确认弹窗 -->
    <view class="confirm-popup" v-if="deleteVisible">
      <view class="mask" @click="deleteVisible = false"></view>
      <view class="confirm-content" style="background-color: #fff;z-index: 100;" >
        
        <view class="confirm-text">确定要删除<strong>{{deleteSchoolName}}</strong>吗？此操作不可撤销</view>
        <view class="confirm-footer">
          <view class="btn cancel-btn" @click="deleteVisible = false">取消</view>
          <view class="btn delete-btn" @click="handleDelete">删除</view>
        </view>
      </view>
    </view>
    
    <!-- 学校列表 -->
    <view class="school-list-container">
      <view class="empty-state" v-if="filteredSchools.length === 0 && isLoaded">
        <image class="empty-icon" src="/static/images/empty.png" mode="aspectFit"></image>
        <text class="empty-text">{{searchKey ? '未找到相关学校' : '暂无学校数据'}}</text>
        <view class="add-new-btn" @click="openForm('add')">
          <text class="iconfont icon-plus"></text>
          <text>添加学校</text>
        </view>
      </view>
      
      <view class="school-list" v-else>
        <view 
          class="school-card" 
          v-for="school in filteredSchools" 
          :key="school.school_id"
          @click.stop.prevent="openForm('edit', school)"
        >
          <view class="card-header">
            <text class="school-name">{{school.school_name}}</text>
            <text class="create-time">{{formatDate(school.create_time)}}</text>
          </view>
          <view class="card-info">
            <view class="info-row">
              <text class="info-label">所在城市：</text>
              <text class="info-value">{{school.city_name}}</text>
            </view>
          </view>
          <view class="card-actions">
            <text class="action-btn edit-btn" @click.stop="openForm('edit', school)">
              <text class="iconfont icon-edit">编辑</text>
            </text>
            <text class="action-btn delete-btn" @click.stop="showDeleteConfirm(school)">
              <text class="iconfont icon-delete">删除</text>
            </text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 加载中 -->
    <view class="loading" v-if="!isLoaded">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>
    
    <!-- 操作提示 -->
    <view class="toast" v-if="toastVisible">{{toastMsg}}</view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      schools: [], // 所有学校数据
      filteredSchools: [], // 筛选后的学校数据
      searchKey: '', // 搜索关键词
      filterVisible: false, // 筛选弹窗状态
      formVisible: false, // 表单弹窗状态
      formType: 'add', // 表单类型：add(新增)/edit(编辑)
      formData: {
		  city_id:'',
		  school_name:''
	  }, // 表单数据
      formErrors: {}, // 表单错误信息
      deleteVisible: false, // 删除确认弹窗状态
      deleteSchoolId: '', // 待删除学校ID
      deleteSchoolName: '', // 待删除学校名称
      cities: [],
      users: [ ],
      cityIndex: 0, // 筛选城市索引
      cityFormIndex: 0, // 表单城市索引
      userIndex: 0, // 表单负责人索引
      isLoaded: false, // 数据加载状态
      debounceTimer: null, // 防抖定时器
      toastVisible: false, // 提示框状态
      toastMsg: '' ,// 提示信息
	  page:1,
	  limit:10,
	  list:[],
	  total:0,
	  hasMore:true
    }
  },
  onLoad() {
    this.getCity();
	this.getSchool()
  },
  onReachBottom() {
	if(!this.isLoaded && this.hasMore){
		console.log('触底')
	}
  	if(this.total > this.filteredSchools.length){
		this.page ++
		this.getSchool()
	}
  },
  onPullDownRefresh() {
  	this.page = 1
	this.filteredSchools = []
	this.hasMore = true
	this.isLoaded = true
	this.getSchool()
	uni.stopPullDownRefresh()
  },
  methods: {
	  async getCity(){
	  	const res = await this.$api.get('/City/index','',true)
	  	if(res.data.code === 200) {
	  		res.data.data.forEach(item => {
	  			this.cities.push(item.city_name)
	  		})
	  		this.list = res.data.data
			this.formData.city_id = this.list[this.cityFormIndex].city_id
	  	}
	  	
	  },
    
    async getSchool(){
		const res = await this.$api.get('/School/index',{page:this.page,limit:this.limit},true)
		if(res.data.code === 200) {
			let  data = res.data.data
			if(data.length === 0 ){
				this.hasMore = false
			}
			this.filteredSchools = this.filteredSchools.concat(data)
			this.total = data.total
			if(this.total > data.length){
				this.hasMore = true
			}
			this.isLoaded = true
		}
	},
    // 搜索防抖
    debounceSearch() {
      if (this.debounceTimer) clearTimeout(this.debounceTimer);
      this.debounceTimer = setTimeout(() => {
      }, 300);
    },
    
    // 显示筛选弹窗
    showFilter() {
      this.filterVisible = true;
    },
    
    // 城市筛选变更
    onCityChange(e) {
      this.cityIndex = e.detail.value;
    },
    
    // 表单城市变更
    onFormCityChange(e) {
	 
      this.cityFormIndex = e.detail.value;
	  console.log('dasdadada',this.cityFormIndex)
	  this.formData.city_id = this.list[this.cityFormIndex].city_id
    },
    
    // 负责人变更
    onUserChange(e) {
      this.userIndex = e.detail.value;
    },
    
    // 应用筛选
    applyFilter() {
    
      this.filteredSchools = this.schools.filter(school => {
        // 搜索筛选
        const searchMatch = this.searchKey 
          ? school.school_name.includes(this.searchKey) 
          : true;
          
        // 城市筛选
        const cityMatch = cityId 
          ? school.city_id === cityId 
          : true;
          
        return searchMatch && cityMatch;
      });
      
      this.filterVisible = false;
    },
    
    // 打开表单
    openForm(type, school = null) {
      this.formType = type;
      
      if (type === 'add') {
        // 新增表单初始化
        this.formData = {
          school_id: '',
          city_id: '',
          user_id: '',
          school_name: ''
        };
        this.cityFormIndex = 0;
        this.userIndex = 0;
      } else {
        // 编辑表单初始化
        this.formData = { ...school };
        
        // 设置城市索引
        
        
        // 设置负责人索引
        const userIndex = this.users.findIndex(u => u.id === school.user_id);
        this.userIndex = userIndex !== -1 ? userIndex : 0;
      }
      
      this.formVisible = true;
    },
    
    // 关闭表单
    closeForm() {
      this.formVisible = false;
      this.formErrors = {};
    },
    
    // 提交表单
    async submitForm() {
      this.formErrors = {};
      
      // 表单验证
      if (!this.formData.school_name) {
		uni.showToast({
				icon:'none',
				title:'请输入学校名称'
		})
        return;
      }
      
      
      if (!this.formData.city_id) {
        uni.showToast({
        		icon:'none',
        		title:'选择城市'
        })
        return;
      }

      if (this.formType === 'add') {
        // 新增逻辑

        
        // 添加到列表
        this.schools.unshift({ ...this.formData });
		delete this.formData.school_id,
		delete this.formData.user_id
        const res = await this.$api.post('/School/save',this.formData,true)
		if(res.data.code === 200) {
			uni.showToast({icon:'none',title:'添加成功'});
			this.filteredSchools = []
			this.getSchool()
		}
      } else {
        // 编辑逻辑
        const res = await this.$api.post('/School/update',this.formData,true)
		if(res.data.code === 200) {
			uni.showToast({icon:'none',title:'编辑成功'});
			this.filteredSchools = []
			this.getSchool()
		}
      }
      
      // 关闭表单
      this.formVisible = false;
    },
    
    // 显示删除确认
    showDeleteConfirm(school) {
      this.deleteSchoolId = school.school_id;
      this.deleteSchoolName = school.school_name;
      // this.deleteVisible = true;
	  uni.showModal({
	  	confirmText:'确认删除',
		title:'温馨提示',
		content:`您是否确定要删除${school.school_name}吗？此操作不可撤销`,
		success: async (res)  => {
			if(res.confirm){
				const respone = await this.$api.post('/School/delete',{school_id:this.deleteSchoolId},true)
				if(respone.data.code === 200) {
					uni.showToast({icon:'none',title:'删除成功'});
					this.filteredSchools = []
					this.getSchool()
				}
			}
		}
	  })
    },
    
   

    
    // 获取负责人名称
    getUserName(userId) {
      const user = this.users.find(u => u.id === userId);
      return user ? user.name : '未知负责人';
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '未知时间';
      const date = new Date(dateStr);
      return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    },
    
    // 显示提示
    showToast(msg) {
      this.toastMsg = msg;
      this.toastVisible = true;
      
      setTimeout(() => {
        this.toastVisible = false;
      }, 2000);
    }
  }
}
</script>

<style lang="scss" scoped>
/* 全局样式 */

.container {
  padding: 30rpx;
}

/* 头部样式 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.header-title {
  font-size: 40rpx;
  font-weight: 600;
  color: #333;
}

.add-btn {
  display: flex;
  align-items: center;
  background-color: #409EFF;
  color: #fff;
  height: 88rpx;
  border-radius: 44rpx;
  padding: 0 30rpx;
  font-size: 28rpx;
  box-shadow: 0 4rpx 12rpx rgba(64, 158, 255, 0.3);
}

.add-btn .icon-plus {
  margin-right: 10rpx;
  font-size: 32rpx;
}

/* 搜索与筛选样式 */
.search-filter {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.search-box {
  flex: 1;
  display: flex;
  align-items: center;
  background-color: #fff;
  height: 88rpx;
  border-radius: 44rpx;
  padding: 0 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.search-box .icon-search {
  font-size: 32rpx;
  color: #909399;
  margin-right: 20rpx;
}

.search-box input {
  flex: 1;
  height: 88rpx;
  font-size: 28rpx;
  color: #333;
  background-color: transparent;
  border: none;
  outline: none;
}

.filter-btn {
  width: 88rpx;
  height: 88rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #fff;
  border-radius: 44rpx;
  margin-left: 20rpx;
  font-size: 32rpx;
  color: #909399;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

/* 弹窗样式 */
.mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 100;
}

.filter-popup,
.form-popup,
.confirm-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 101;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
}

.filter-content,
.form-content,
.confirm-content {
  background-color: #fff;
  border-radius: 30rpx;
  width: 600rpx;
  box-shadow: 0 12rpx 30rpx rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.filter-header,
.form-header,
.confirm-header {
  padding: 40rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-title,
.form-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
}

.close-btn {
  font-size: 40rpx;
  color: #909399;
}

.filter-body,
.form-body {
  padding: 40rpx 30rpx;
}

.filter-item,
.form-group {
  margin-bottom: 40rpx;
}

.filter-label,
.form-label {
  display: block;
  font-size: 28rpx;
  color: #606266;
  margin-bottom: 20rpx;
}

.picker-container,
.picker-input {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 90rpx;
  background-color: #f5f7fa;
  border-radius: 16rpx;
  padding: 0 30rpx;
  font-size: 28rpx;
  color: #333;
}

.form-input {
  width: 100%;
  height: 90rpx;
  font-size: 28rpx;
  color: #333;
  padding: 0 30rpx;
  background-color: #f5f7fa;
  border-radius: 16rpx;
  box-sizing: border-box;
  border: none;
  outline: none;
}

.form-input.error {
  border: 1rpx solid #f56c6c;
}

.error-tip {
  font-size: 24rpx;
  color: #f56c6c;
  margin-top: 10rpx;
}

.filter-footer,
.form-footer,
.confirm-footer {
  padding: 30rpx;
  display: flex;
  justify-content: flex-end;
  border-top: 1rpx solid #f0f0f0;
}

.btn {
  height: 88rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 44rpx;
  font-size: 28rpx;
  padding: 0 40rpx;
  margin-left: 20rpx;
}

.cancel-btn {
  color: #606266;
  background-color: #f5f7fa;
}

.confirm-btn {
  color: #fff;
  background-color: #409EFF;
}

.delete-btn {
  color: #fff;
  // background-color: #e64340;
}

/* 确认弹窗样式 */
.confirm-content {
  padding: 60rpx 40rpx;
  text-align: center;
}

.confirm-icon {
  font-size: 100rpx;
  color: #e6a23c;
  margin-bottom: 30rpx;
}

.confirm-text {
  font-size: 32rpx;
  color: #333;
  margin-bottom: 60rpx;
}

.confirm-text strong {
  color: #e64340;
}

/* 学校列表样式 */
.school-list-container {
  margin-bottom: 100rpx;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;
  color: #909399;
}

.empty-icon {
  width: 240rpx;
  height: 240rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 28rpx;
  margin-bottom: 40rpx;
}

.add-new-btn {
  display: flex;
  align-items: center;
  background-color: #409EFF;
  color: #fff;
  height: 90rpx;
  border-radius: 45rpx;
  padding: 0 40rpx;
  font-size: 28rpx;
}

.add-new-btn .icon-plus {
  margin-right: 10rpx;
  font-size: 32rpx;
}

.school-list {
  display: flex;
  flex-direction: column;
  gap: 30rpx;
}

.school-card {
  background-color: #fff;
  border-radius: 24rpx;
  overflow: hidden;
  box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
  position: relative;
  padding-bottom: 20rpx;
}

.school-card:hover {
  transform: translateY(-5rpx);
  box-shadow: 0 12rpx 30rpx rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.school-name {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.create-time {
  font-size: 24rpx;
  color: #909399;
}

.card-info {
  padding: 30rpx;
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.info-label {
  font-size: 26rpx;
  color: #606266;
  width: 160rpx;
}

.info-value {
  font-size: 28rpx;
  color: #333;
  flex: 1;
}

.card-actions {
  position: absolute;
  right: 30rpx;
  bottom: 20rpx;
  display: flex;
  gap: 20rpx;
}

.action-btn {
  width: 70rpx;
  height: 40rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 32rpx;
}

.edit-btn {
  color: #409EFF;
  // background-color: rgba(64, 158, 255, 0.1);
}

.delete-btn {
  color: #e64340;
  // background-color: rgba(230, 67, 64, 0.1);
}

/* 加载中样式 */
.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 150rpx 0;
}

.loading-spinner {
  width: 100rpx;
  height: 100rpx;
  border: 6rpx solid #f3f3f3;
  border-top: 6rpx solid #409EFF;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #909399;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 提示框样式 */
.toast {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(0, 0, 0, 0.7);
  color: #fff;
  padding: 24rpx 40rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
  z-index: 1000;
}
</style>